package com.boot.message.netty.server.handler.impl;

import com.boot.message.netty.server.handler.BaseServerHandler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * @author 霜寒 <1621856595@qq.com>
 * @date 2020/3/14 18:59
 **/
@Slf4j
@ChannelHandler.Sharable
public class StringServerHandler extends BaseServerHandler {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("连接成功");
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            String message = null;
            if (msg instanceof ByteBuf) {
                ByteBuf readBuffer = (ByteBuf) msg;
                byte[] data = new byte[readBuffer.readableBytes()];
                readBuffer.readBytes(data);
                message = new String(data, StandardCharsets.UTF_8);
            } else if (msg instanceof String) {
                message = (String) msg;
            }
            System.out.println("from client : " + message);
            if ("exit".equals(message)) {
                ctx.close();
                return;
            }
            String line = "自动回复...";
            ctx.writeAndFlush(line);
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        log.error("连接出错,连接已断开");
        ctx.close();
    }


}